<?php
/**
 * Created by PhpStorm.
 * User: ljhint
 * Date: 2021/3/8
 * Time: 16:11
 */

namespace App\Console\Commands;


use App\Models\VehicleBrand;
use App\Models\VehicleConfigure;
use App\Models\VehicleModel;
use App\Models\VehicleStyle;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use OSS\OssClient;

class AutoHomeData extends Command
{
    public $signature = 'Caiji:Autohome {type}';
    protected $description = '采集汽车之家数据';

    public function handle(){
        set_time_limit(0);
        if($this->argument('type') == 'Brand'){
            $this->vehicleBrandData();
        }elseif ($this->argument('type') == 'Model'){
            $this->vehicleModelData();
        }elseif ($this->argument('type') == 'Style'){
            $this->vehicleStyleData();
        }elseif ($this->argument('type') == 'Configure'){
            $this->vehicleConfigure();
        }elseif ($this->argument('type') == 'auto'){
            //自动处理
            $this->vehicleBrandData();
            sleep(30);
            $this->vehicleModelData();
            sleep(30);
            $this->vehicleStyleData();
            sleep(30);
            $this->vehicleConfigure();

        }else{
            $this->error('Something went wrong!');
        }
        $this->info('ok!');
    }

    /**
     * vehicleBrandData 品牌数据
     * Created by ljhint on 2020/8/20
     */
    public  function vehicleBrandData()
    {
        $url = 'https://dealer.autohome.com.cn/Handler/CarAPIHandler.ashx?act=1';
        $result = $this->getUrl($url);
        $array = json_decode($this->get_between($result,'(',')'),true);
        foreach ($array['result']['branditems'] as $v) {
            VehicleBrand::updateOrCreate(
                ['brandId'=>$v['id']],
                [ 'brandName'=>$v['name'], 'bfirstletter'=>$v['bfirstletter'],'country'=>$v['country'],'countryid'=>$v['countryid']]
            );
            if (VehicleBrand::where('brandId',$v['id'])->value('logoUrl') == NULL){
                $logo = $this->downloadLogoImg($v['logo']);
                if ($logo){
                    VehicleBrand::where('brandId',$v['id'])->update(['logoUrl' => $logo]);
                }
            }
        }
        //Log::info('品牌更新时间为.',[date('Y-m-d H:i:s').'更新状态为成功']);
    }

    /**
     * downloadLogoImg 下载汽车logo
     * Created by ljhint on 2020/8/20
     * @param $url
     * @return bool|string
     */
    private function downloadLogoImg($url)
    {
        try {
            $newFile = "upload/logo/".time()."_".uniqid().".".pathinfo($url, PATHINFO_EXTENSION);
            $OSS = new ossClient(config('oss.access_id'), config('oss.access_key'), config('oss.endpoint'));
            $res = $OSS->putObject(config('oss.bucket'),$newFile,$this->getUrl($url));
            return config('oss.cdnDomain').$newFile;
        } catch (\Exception $e) {
            Log::info('下载品牌logo时间为.',[date('Y-m-d H:i:s').'下载状态为失败']);
            return false;
        }
    }

    /**
     * vehicleModelData 汽车车型
     * Created by ljhint on 2020/8/20
     */
    public function vehicleModelData(){
        $brands = VehicleBrand::all();
        foreach ($brands as $brand){
            $id = $brand->brandId;
            $url = 'https://dealer.autohome.com.cn/Handler/CarAPIHandler.ashx?act=2&brandid='.$id;
            $result = $this->getUrl($url);
            $result = substr($result,1,-1);
            $data = $this->decode($result);
            $array = $data['result']['factoryitems'];
            foreach ($array as $value){
                $arr = [];
                $arr['brandId']=$id;
                $arr['factoryiTemsId'] = $value['id'];
                $arr['factoryName'] = $value['name'];
                $arr['factoryFirstletter'] = $value['firstletter'];
                foreach ($value['seriesitems'] as $v){
                    $arr['seriesId'] = $v['id'];
                    $arr['seriesName'] = $v['name'];
                    $arr['seriesFirstLetter'] = $v['firstletter'];
                    $arr['seriesstate'] = $v['seriesstate'];
                    $arr['seriesorder'] = $v['seriesorder'];
                    VehicleModel::updateOrCreate(
                        ['seriesId'=>$v['id']],$arr
                    );
                }
            }
            sleep(2);
        }
        //Log::info('车型更新时间为.',[date('Y-m-d H:i:s').'更新状态为成功']);
    }

    /**
     * vehicleStyleData 更新车款式
     * Created by ljhint on 2020/8/20
     */
    public function vehicleStyleData(){
        $models = VehicleModel::all();
        foreach ($models as $model){
            $id = $model->seriesId;
            $url = 'https://dealer.autohome.com.cn/Handler/CarAPIHandler.ashx?act=3&seriesid='.$id;
            $result = $this->getUrl($url);
            $result = substr($result,1,-1);
            $data = $this->decode($result);
            $array = $data['result']['yearitems'];
            if (is_array($array)){
                foreach ($array as $value){
                    $arr = [];
                    $arr['seriesId'] = $id;
                    $arr['vehicleYearItemsId'] = $value['id'];
                    $arr['vehicleYearName'] = $value['name'];
                    foreach ($value['specitems'] as $v){
                        $arr['specId'] = $v['id'];
                        $arr['specName'] = $v['name'];
                        $arr['state'] = $v['state'];
                        $arr['minprice'] = $v['minprice'];
                        $arr['maxprice'] = $v['maxprice'];
                        VehicleStyle::updateOrCreate(
                            ['specId'=>$v['id']],$arr
                        );
                    }
                }
            }
            sleep(2);
        }
        //Log::info('款式更新时间为.',[date('Y-m-d H:i:s').'更新状态为成功']);
    }

    /**
     * vehicleConfigure 更新配置
     * Created by ljhint on 2020/8/20
     */
    public function vehicleConfigure()
    {
        $styles = VehicleStyle::all();
        foreach ($styles as $style) {
            $array = [];
            $id = $style->specId;
            $url = 'https://car.m.autohome.com.cn/ashx/car/GetModelConfig.ashx?ids=' . $id;
            $result = $this->getUrl($url);
            $result = json_decode($result, true);
            $array['specId'] = $id;
            $array['styleIds'] = $style->seriesId;
            $array['param'] = json_encode($result['param'],JSON_UNESCAPED_UNICODE);
            $array['config'] = json_encode($result['config'],JSON_UNESCAPED_UNICODE);
            $array['specitems'] = json_encode($result['specitems'],JSON_UNESCAPED_UNICODE);
            VehicleConfigure::updateOrCreate(
                ['specId'=>$id],$array
            );
            sleep(2);
        }
        //Log::info('配置更新时间为.',[date('Y-m-d H:i:s').'更新状态为成功']);
    }


    private function downloadImg($url)
    {
        try {
            $newFile = "upload/".date('Ymd')."/".time()."_".uniqid().".".pathinfo($url, PATHINFO_EXTENSION);
            $OSS = new ossClient(config('oss.access_id'), config('oss.access_key'), config('oss.endpoint'));
            $res = $OSS->putObject(config('oss.bucket'),$newFile,$this->getUrl($url));
            return config('oss.cdnDomain').$newFile;
        } catch (\Exception $e) {
            Log::info('下载图片时间为.',[date('Y-m-d H:i:s').'下载状态为失败']);
            return false;
        }
    }

    /**
     * @param $input
     * @param $start
     * @param $end
     * @return bool|string
     * 截取数组中的某一段数据
     */
    public  function get_between($input, $start, $end)
    {
        return substr($input, strlen($start) + strpos($input, $start), (strlen($input) - strpos($input, $end)) * (-1));
    }

    protected function decode($data)
    {
        return json_decode($data, true, 512, JSON_BIGINT_AS_STRING);
    }

    protected function getUrl($url){
        $header = array (
            "Content-Type: application/json",
            "Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7"
        );
        $ch = curl_init ();
        curl_setopt ($ch, CURLOPT_URL, $url );
        curl_setopt ($ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
        $content = curl_exec ( $ch );
        if ($content == FALSE) {
            return curl_error ( $ch );
        }
        curl_close ( $ch );
        return $content;
    }
}
